#include <assert.h>
#include "magicarray.h"

MagicArray::MagicArray()
: m_capacity(2000)
{
}

MagicArray::~MagicArray()
{
}


void MagicArray::reset()
{
    m_startIndex = -1;
    m_endIndex = -1;
}

void MagicArray::recapacity(int capacity)
{
    if (m_data)
        delete []m_data;
    m_data= new double[capacity];
    m_capacity = capacity;
    reset();
}

double& MagicArray::getElem(const int index)
{
    assert(index >= 0 && index < m_arraySize);
    if ((index < m_endIndex || index > m_startIndex) && index >= 0 && index < m_arraySize) {
        loadArray(index);
    }
    return m_data[m_arraySize - 1 - (index-m_endIndex)];
}

void MagicArray::loadArray(int index)
{
    index += m_capacity / 2;
    if (index < 0) {
        index = 0;
    }
    else if (index > m_arraySize - 1)
        index = m_arraySize - 1;
    m_startIndex = index;
    m_endIndex = m_startIndex - m_capacity;
}